package com.example.springbootuploaddemo.upload;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传
 */
@RestController
public class UploadApi {

    @Value("${file.address}")
    private String address;
    private String path = "/file";
    //    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");//线程不安全
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("/yyyy/MM/dd/");//线程安全
    //格式化：日期-->字符串
    LocalDateTime now = LocalDateTime.now();


    @PostMapping("/upload")
    public Map<String, Object> upload(MultipartFile file, HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        String originName = file.getOriginalFilename();
        if (!originName.endsWith(".pdf")) {
            result.put("status", "error");
            result.put("msg", "文件类型不对");
            return result;
        }

//        String format = sdf.format(new Date());
        String format = formatter.format(now);
//        String realPath = request.getServletContext().getRealPath("/") + format;
        String realPath = address + format;

        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        String newName = UUID.randomUUID().toString() + ".pdf";
        try {
            file.transferTo(new File(folder, newName));
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + format + newName;
            result.put("status", "success");
            result.put("url", url);

        } catch (IOException e) {
            e.printStackTrace();
            result.put("status", "error");
            result.put("msg", e.getMessage());
        }

        return result;

    }


    public static void main(String[] args) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("/yyyy/MM/dd/");
        //格式化：日期-->字符串
        LocalDateTime now = LocalDateTime.now();
        String str1 = formatter.format(now);


        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String format2 = sdf.format(new Date());

        System.out.println("--1" + str1);

        System.out.println("--2" + format2);
    }
}
